#include "config.hpp"

#include <commons/file/file.hpp>

#include <fstream>
#include <iostream>

Config &Config::ins()
{
    static Config config;
    return config;
}

sros::RetBool Config::init(const std::string &filename)
{
    if (filename.empty())
    {
        return {false, "filename is empty"};
    }
    
    std::lock_guard<std::mutex> lk(mtx_);
    file_ = std::make_shared<sros::File>(filename);
    return {true};
}

sros::RetBool Config::load(Cfg &cfg)
{
    std::lock_guard<std::mutex> lk(mtx_);
    if (!file_)
    {
        return {false, "config file point is nullptr"};
    }
    
    std::string content;
    auto ret = file_->read_all(content);
    if (!ret.v)
    {
        return {ret.v, "config file" + ret.msg};
    }
    
    if (content.empty())
    {
        return {false, "config file content is empty"};
    }
    
    try
    {
        cfg = nlohmann::json::parse(content).get<Cfg>();
    }
    catch(const std::exception& e)
    {
        return {false, e.what()};
    }
    
    return {true};
}

sros::RetBool Config::save(const Cfg &cfg)
{
    std::lock_guard<std::mutex> lk(mtx_);
    
    if (!file_)
    {
        return {false, "config file point is nullptr"};
    }
    
    nlohmann::json j = cfg;
    auto ret = file_->write(j.dump(4));
    
    return {ret.v, "config file " + ret.msg};
}

